# app/core/database.py
import redis
import sqlite3
import chromadb
import contextlib
from app.core.config import settings

# Redis连接
redis_client = redis.Redis(
    host=settings.REDIS_HOST,
    port=settings.REDIS_PORT,
    db=settings.REDIS_DB,
    decode_responses=False
)

# ChromaDB客户端
chromadb_client = chromadb.PersistentClient(path=settings.CHROMA_DB_PATH)


@contextlib.contextmanager
def get_db_connection(db_path: str, timeout: float = 20.0):
    conn = sqlite3.connect(db_path, timeout=timeout)
    try:
        yield conn
    except Exception:
        conn.rollback()
        raise
    else:
        conn.commit()
    finally:
        conn.close()
